// User/pages/Record/index.js  
const app = getApp();
import {
    showToast, logger
} from '@/utils/util';
import {
    fetchElderlyInfo,
    fetchOperationHistory,
    fetchMedicationHistory,
    fetchAllergyHistory,
    fetchFamilyHistory,
    fetchPastHistory
} from '@/services/personal';
import { customNavigate } from '@/utils/route'

Page({

    /**  
     * 页面的初始数据  
     */
    data: {
        popup_show: false,
        STATIC_PREFIX: app.globalData.STATIC_PREFIX,
        userInfo: [],
        user_info: null,
        title: '手术史',
        historyInfo: [{
            icon: app.globalData.STATIC_PREFIX + '/static/images/icon_profile_operation.png',
            name: '手术史',
            path: 'fetchOperationHistory'
        }, {
            icon: app.globalData.STATIC_PREFIX + '/static/images/icon_profile_medicate.png',
            name: '用药史',
            path: 'fetchMedicationHistory'
        }, {
            icon: app.globalData.STATIC_PREFIX + '/static/images/icon_profile_allergy.png',
            name: '过敏史',
            path: 'fetchAllergyHistory'
        }, {
            icon: app.globalData.STATIC_PREFIX + '/static/images/icon_profile_family.png',
            name: '家族史',
            path: 'fetchFamilyHistory'
        }, {
            icon: app.globalData.STATIC_PREFIX + '/static/images/icon_profile_history.png',
            name: '既往病史',
            path: 'fetchPastHistory'
        }],
        steps: []
    },

    /**  
     * 生命周期函数--监听页面加载  
     */
    async onShow() {
        const res = await fetchElderlyInfo({
            id: wx.getStorageSync('elderlyInfo').id
        });
        this.setData({
            userInfo: this.renderTemplate(res.data),
            user_info: res.data
        });
    },

    renderTemplate(res) {
        const valueMap = {
            name: '姓名',
            sex: '性别',
            age: '年龄',
            national: '民族',
            blood_type: '血型',
            phone: '电话',
            native_place: '籍贯',
            id_number: '身份证号',
            address: '家庭住址'
        };
    
        const userInfo = [];
    
        const getSexValue = (sex) => {
            if (sex === 0) return '女';
            if (sex === 1) return '男';
            return '';
        };
    
        Object.keys(valueMap).forEach(item => {
            // 如果是身份证号或籍贯，并且 `is_applet_register` 为 1
            if ((item === 'id_number' || item === 'native_place') && res.is_applet_register == 1) {
                return; // 直接跳过本次循环
            }

            const obj = {
                key: valueMap[item],
                value: res[item]
            };
    
            // 处理性别字段
            if (item === 'sex') {
                obj.value = getSexValue(res[item]);
            }
    
            userInfo.push(obj);
        });
    
        return userInfo;
    },

    async onClickItem(event) {
        const {
            item
        } = event.currentTarget.dataset;

        // 创建接口映射对象  
        const apiMapping = {
            fetchOperationHistory,
            fetchMedicationHistory,
            fetchAllergyHistory,
            fetchFamilyHistory,
            fetchPastHistory
        };
        const resultMapping = {
            '手术史': ['operation_name', 'operation_time'],
            '用药史': ['drug_name', 'drug_time'],
            '过敏史': ['allergen_name', 'create_time'],
            '家族史': ['disease_name', 'create_time'],
            '既往病史': ['disease_name', 'confirmed_time']
        }

        // 执行相应的接口调用  
        const apiFunction = apiMapping[item.path];

        if (apiFunction) {
            try {
                const res = await apiFunction({
                    id: wx.getStorageSync('userInfo').id
                });
                if (res.return_code == 'SUCCESS') {
                    this.setData({
                        popup_show: true,
                        title: item.name,
                        steps: res.data.map(key => {
                            return {
                                text: key[resultMapping[item.name][1]],
                                desc: key[resultMapping[item.name][0]]
                            }
                        })
                    })
                }
                // 这里可以处理和展示相应的数据  
            } catch (error) {
                showToast('获取数据异常')
            }
        } else {
            logger.warn("未定义的路径:", item.path);
        }
    },
    onEdit() {
        customNavigate({
            url: '/User/pages/Register/index',
            params: {
                type: 'edit'
            }
        })
    },
    onClose() {
        this.setData({
            popup_show: false
        })
    },
    /**  
     * 用户点击右上角分享  
     */
    onShareAppMessage() {}
});